# -*- encoding: utf-8 -*-
import datetime

from django import forms
from django.utils.translation import ugettext as _

class DateForm(forms.Form):
    date = forms.DateTimeField(label=_(u'Date'),
                               initial=datetime.datetime.now().strftime('%d/%m/%Y %H:%M'),
                               input_formats=('%d/%m/%Y %H:%M', '%d/%m/%Y %H:%M:%S' , '%d/%m/%y %H:%M', '%d/%m/%y %H:%M:%S'))


class TimeField(forms.IntegerField):
    """A field to get a time and return it in seconds"""
    def __init__(self, *args, **kwargs):
        super(TimeField, self).__init__(self, *args, **kwargs)

    def clean(self, value):
        import re
        value = value.strip()
        if not value:
            return
        time_matchers = [re.compile(ur"^(?P<hour>\d)h(?P<minute>[0-5]?\d)$"),
                         re.compile(ur"^(?P<hour>\d):(?P<minute>[0-5]\d):(?P<second>[0-5]\d)$"),
                         re.compile(ur"^(?P<minute>[0-5]\d)\'((?P<second>[0-5]\d)\'\')?$")]
        for time_matcher in time_matchers:
            match = time_matcher.match(value)
            if match:
                break
        if match:
            matchdict = match.groupdict()
            hours = int(matchdict.get('hour', 0))
            minutes = int(matchdict.get('minute', 0))
            seconds = int(matchdict.get('seconds', 0))
            time = hours*3600 + minutes * 60 + seconds
            return super(TimeField, self).clean(time)
        else:
            raise forms.ValidationError(_(u"Not a valid time format"))


class UniversalFloatField(forms.FloatField):
    """"The UniversalFloatField is a Float Field who accept '.' and ',' as a separator."""
    def __init__(self, *args, **kwargs):
        super(UniversalFloatField, self).__init__(*args, **kwargs)

    def clean(self, value):
        value = value.replace(',', '.')
        return super(UniversalFloatField, self).clean(value)
